package constant.milk.periodapp.alarm;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import constant.milk.periodapp.IntroActivity;
import constant.milk.periodapp.R;
import constant.milk.periodapp.bean.SengriData;
import constant.milk.periodapp.database.DBSelectQuery;
import constant.milk.periodapp.database.DbAdapter;
import constant.milk.periodapp.util.MilkShared;
import constant.milk.periodapp.util.MilkUtil;

public class AlarmBroadcast extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent)
	{
		// 인스턴스를 가져온다
//		Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);  
		// 파라미터로 0 취소할떄 까지 무한반복을 나타낸다. -1 한번만 실행된다.
		
		// 시작은 0 이므로 즉시 실행되고 진동 200 milliseconds, 멈춤 500 milliseconds 된다
//		long [] pattern = {0, 2000};
//		v.vibrate(pattern, -1); 
		
		// 알림 사운드 리스트를 가져올 수 있구요.
//		RingtoneManager rm = new RingtoneManager(context);
//		rm.setType(RingtoneManager.TYPE_NOTIFICATION);
//		Cursor c = rm.getCursor();

		// 설정된 알림사운드를 가져와서 재생할 수 있습니다.
		Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION);
//		Ringtone ringtone = RingtoneManager.getRingtone(acontext, ringtoneUri);

		// 노티바에 뛰우기
		NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		String title = context.getString(R.string.appname) + " 알람";
		
		String message = "마법의 그날이 하루 남았습니다.";
		
		NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
		
		builder.setSmallIcon(R.drawable.ic_period);
        builder.setContentTitle(title);
        builder.setContentText(message);
        builder.setAutoCancel(true); // 알림바에서 자동 삭제
        builder.setSound(ringtoneUri);
        
        Intent intent2 = new Intent(context, IntroActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context.getApplicationContext(), 
        		0, intent2, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(pIntent);
		
        nm.notify(0, builder.build());
        
        MilkAlarm ma = new MilkAlarm();
        MilkShared s = new MilkShared(context);
        int alarm = s.getAlarm();

		if (alarm == 0)
		{
			ma.stopAlarm(context);
			return;
		}
		
		DbAdapter db = DbAdapter.getInstance();
		DBSelectQuery select = new DBSelectQuery(context, db);
		
		ArrayList<SengriData> list = new ArrayList<SengriData>();
		list = select.getSengriList();
		
		if (list.size() < 1)
		{
			ma.stopAlarm(context);
			return;
		}

		// 오늘날짜
		Calendar cal1 = Calendar.getInstance();
		
		int term = s.getSengriTerm();
		
		if (s.getSengriType() == 0)
		{
			term = s.getSengriTerm();
		}
		else
		{
			term = MilkUtil.getAveSengriTerm(context, select);
		}
		
		cal1.add(Calendar.DAY_OF_MONTH, term);
		
		long alarmMill = cal1.getTimeInMillis();
		
		Intent intent3 = new Intent(context, AlarmBroadcast.class);
		PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent3,
				PendingIntent.FLAG_CANCEL_CURRENT);

		AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		manager.cancel(sender);
		
		int version = Build.VERSION.SDK_INT;
		
		if (version >= 19)
		{
			manager.setExact(AlarmManager.RTC_WAKEUP, alarmMill, sender);
		}
		else
		{
			manager.set(AlarmManager.RTC_WAKEUP, alarmMill, sender);
		}
        
//        ringtone.play();
	}
}
